<?php
    require_once ("Includes/session.php");
    require_once ("Includes/simplecms-config.php"); 
    require_once ("Includes/connectDB.php");
    require_once ("Functions/scanresults.php");
    require_once ("Functions/database.php");
    require_once ("Includes/error.php");
    confirm_logged_on();
    include("Includes/header.php"); 

    // small helper function for uploading files 
    // made so we can return instead of using lots of if else
    function file_upload() {
        global $errors;

        if ($_FILES['file']['error']) {
            array_push($errors, 'Error: file upload failed');
            return;
        }

        if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
            array_push($errors, 'Error: How are you accessing an non-uploaded file?');
            return;
        }
    }

    if (isset($_POST['submit']))
    {
        if ($_POST['submit'] == 'Upload File') {
            if ($_FILES['file']['error']) {
                $error = 'Error: File upload failed, full file never reached server';
            } else if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
                $error = 'Error: How are you accessing an non-uploaded file?';
            } else if (!($meet = parseAPFile($tmp_name = $_FILES['file']['tmp_name']))){
                $error = 'Error: File unable to be fully parsed';
            } else {
                // save results file for database restore
                $date = new DateTime($meet['date']);
                $date = $date->format('Y-m-d');
                $new_filename = $date.'_'.preg_replace('~\W+~', '', $meet['metadata']['name']).'.results';
                if (!move_uploaded_file($tmp_name, ROOT_DIR.'Results/Cabana/'.$new_filename)) {
                    $error = 'Error: Results file could not be saved, meet not added';
                } else {
                    $meet['filename'] = $new_filename;
                    addWholeMeet($meet, $_SESSION['userid']);
                    $msg = "'".$meet['metadata']['name']."' on ".$meet['date']." successfully added";
                }
            }
        }
        else if  ($_POST['submit'] == 'Testing One Add') {
            $scores = parseAPFile(ROOT_DIR.'Results/Cabana/APFile_meet84.results');
            if ($scores === FALSE) {
                $error = "Error: Couldn't fully parse file";
            } else {
                addWholeMeet($scores);
            }  
        }
        else if ($_POST['submit'] == 'Test Scan Result Files') {
            testScanResults('Cabana');
            echo REGEX_RELAY;
            echo REGEX_SINGLE;
        }
        else if ($_POST['submit'] == 'Clear Database'){
            clearTables();
        }
        else if ($_POST['submit'] == 'Create Init File') {
            setupMetaData('Cabana', $createDir = FALSE);
        }
        else if ($_POST['submit'] == 'Scan In Event Names/IDs') {
            scanInEvents(ROOT_DIR.'Results/Cabana/APFile_meet01.results');
        }
        else if ($_POST['submit'] == 'Restore Database') {
            if (testScanResults('Cabana') === FALSE) {
                addError('Error: test scan did not pass');
            } else if (restoreDatabase('Cabana') === FALSE) {
                addError('Error: database only partially restored');
            } else {
                addMsg('Database restoration complete');
            }
        }
        else if ($_POST['submit'] == 'Update All Seed Times') {
            updateSeedTimes(TRUE);
        } 
        else {
            addError('Error: command not found');
        }
    }
?>
<div id="main">
    <h2>Upload Results</h2>
    <?php

        // prints out error msg
        if (isset($error))
            echo '<div class="error">'.$error.'</div>';
        displayErrors();
        if (isset($msg))
            echo '<div class="msg">'.$msg.'</div>'; 
        displayMsg();
    ?>
    <form action="scan.php" method="post" enctype="multipart/form-data">
        <fieldset>
            <legend>Upload Results:</legend>
            <ol>
                <li>
                    <input type="file" name="file" id="file">
                    <input type="submit" name="submit" value="Upload File" />
                </li>
            </ol>
        </fieldset>
    </form>
    <?php if (is_admin()):?>
    <h2>Database Management</h2>
    <form action="scan.php" method="post">
        <fieldset>
            <legend>Database Management:</legend>
            <ol>
                <li>
                    <input type="submit" name="submit" value="Create Init File" />
                    <input type="submit" name="submit" value="Scan In Event Names/IDs" />
                </li>
                <li>
                    <input type="submit" name="submit" value="Update All Seed Times" />
                </li>
                <li>
                    <input type="submit" name="submit" value="Test Scan Result Files" />
                    <input type="submit" name="submit" value="Testing One Add" />
                </li>
            </ol>
        </fieldset>
    </form>
    <h2>Database Wipe and Restore</h2>
    <form action="scan.php" method="post">
        <fieldset>
            <legend>Database Wipe and Restore:</legend>
            <ol>
                <li>
                    <input type="submit" name="submit" value="Restore Database" />
                    <input type="submit" name="submit" value="Clear Database" />
                </li>
            </ol>
        </fieldset>
    </form>
    <?php endif; ?>
</div>
</div> <!-- End of outer-wrapper which opens in header.php -->
<?php include ("Includes/footer.php");?>